<?php namespace Home\Controller;

use Hdphp\Controller\Controller;
/*
 * 订单管理控制器
 */
class OrderController extends Controller
{
	protected $db;
	/**
	 * 构造方法
	 * 
	 */
	 public function __init()
	 {
	 	$this->db = new \Common\Model\Address;
	 }
	/*
	 * 订单首页
	 */
	public function index()
	{
		if(IS_AJAX)
		{
			//p($_POST);die;
			//先清除订单页的缓存
			unset($_SESSION['order']);
			//获得ajax   post提交来的商品唯一id
			$sid = $_POST['id'];
			//p($sid);
			//去除最右边的  竖线
			$sid = rtrim($sid,"|");
			//p($sid);
			//转化为数组
			$sid = explode("|", $sid);
			//p($sid);
			//把超全局变量$_SESSIN['cart']里的商品信息循环压给$_SESSION['order']
			foreach ($sid as $k => $v) {
				$_SESSION['order'][$v] = $_SESSION['cart']['goods'][$v];
			}  
			//p($_SESSION);
			foreach ($_SESSION['order'] as $k => $v) {
				//otions字段内容必须为数组，如果不是将其转化为数组
				if(!is_array($_SESSION['order'][$k]['options']))
				{
					//将其转化为数组
					$_SESSION['order'][$k]['options'] = explode("|", $v['options']);
				}
			}
			//处理成功后输出1
			echo 1;die;
			
		}
		/**
		 *读取数据并分配页面步骤 
		 */
		//判断是否存在
		if(isset($_SESSION['order']))
		{
			//p($_SESSION);
			$orderData = $_SESSION['order'];
			//p($orderData);
			//定义变量本店合计总价
			$lastTotal = 0;
			//统计总价
			foreach ($orderData as $k => $v) {
				$lastTotal = $lastTotal + $v['total'];
			}
			//p($lastTotal);
		}
		
		//分配变量到订单页
		View::with('lastTotal',$lastTotal);
		View::with('orderData',$orderData);
		//读取地址表数据并分配页面
		$addressData = Db::table('address')->where('uid','=',$_SESSION['uid'])->get();
		//p($addressData);			
		//把地址转化为数组
		//给数组追加一个area字段  不让覆盖address
		foreach ($addressData as $k => $v) {
			$addressData[$k]['area'] = explode("|", $v['address']);
		}		
		p($addressData);
		//分配页面
		View::with('addressData',$addressData);
		//载入订单页
		View::make('order');
	}
	/**
	 * 添加新地址
	 */
	public function addAddress()
	{
		if(IS_POST)
		{
			//p($_POST);die;			
			if(!$this->db->store()){
				//添加失败
				View::error($this->db->getError());
			}else{
				//添加成功
				View::success('添加成功',U('Home/Order/index'));
			}
		}
		
	}
}
